package com.lu.pojo.network;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author luzhenfang
 * @date 2020 05 18
 * @description URL类 的简单使用，以及下载网络资源。
 */
public class TestUrl {
    public static void main(String[] args) throws IOException {
        URL url = new URL("https://www.baidu.com/s?wd=java&rsv_spt=1&rsv_iqid=0xe25144f400075d42&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=&tn=baiduhome_pg&ch=&rsv_enter=1&rsv_btype=i&rsv_dl=ib&inputT=518");
        // 协议 主机 端口 路径 参数
        System.out.println(url.getProtocol());
        System.out.println(url.getHost());
        System.out.println(url.getPort());
        System.out.println(url.getPath());
        System.out.println(url.getQuery());
        downloadFile();
    }
    // 下载文件
    public static void downloadFile( ) throws IOException {
        // 连接准备
        URL url = new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589811615462&di=f5c1a1f8a7299ef1d3ee68bd154f542f&imgtype=0&src=http%3A%2F%2Fpic1.16pic.com%2F00%2F51%2F79%2F16pic_5179380_b.jpg");
        URLConnection urlConnection = url.openConnection();
        // 拿到输入流
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("a.png"));
        // 写出文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        // 释放资源
        fos.close();
        inputStream.close();
        ((HttpURLConnection)urlConnection).disconnect();
    }
}
